package cn.le.netty;

import cn.le.bean.vo.NettyServerAddressVO;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.stream.Collectors;

/**
 * netty 获取连接信息工具类
 * Redis数据格式
 * {
 *   "ip": "127.0.0.1",
 *   "port": 8080
 * }
 *
 */
class NettyUtils {

    private static NettyUtils INSTANCE;

    private static String CLIENT = "client";

    @Autowired
    private StringRedisTemplate redisTemplate;

    @PostConstruct
    private void setUp() {
        INSTANCE = this;
    }
    /**
     * 记录netty链接信息
     * @param key
     * @param vo
     */
    public static void setConnect(String key, NettyServerAddressVO vo){
        String json = JSONObject.toJSONString(vo);
        INSTANCE.redisTemplate.opsForHash().put(CLIENT,key,json);
    }

    /**
     * 获取netty链接信息
     * @param key
     * @return
     */
    public static NettyServerAddressVO getConnect(String key){
        String json = (String) INSTANCE.redisTemplate.opsForHash().get(CLIENT,key);
        if (StringUtils.isEmpty(json)){
            return null;
        }
        return JSONObject.parseObject(json, NettyServerAddressVO.class);
    }

    /**
     * 获取netty链接信息
     * @param keys
     * @return
     */
    public static List<NettyServerAddressVO> getConnects(List<Object> keys){
        List<Object> list = INSTANCE.redisTemplate.opsForHash().multiGet(CLIENT,keys);
        //list.removeAll(Collections.singleton(null));//如果keys的数据在Redis中不存在,这里list就存在未null的只,应为ArrayList是可以保存null值的
        if (StringUtils.isEmpty(list)){
            return null;
        }
        List<NettyServerAddressVO> result = new ArrayList<>(list.size());
        for (int i = 0,size = list.size();i < size; i++){
            Object obj = list.get(i);
            if (obj == null){
                continue;
            }
            NettyServerAddressVO vo = JSONObject.parseObject(String.valueOf(obj),NettyServerAddressVO.class);
            result.add(vo);
        }
        return result;
    }
}
